<template>
  <div class="project-create-container">
    <el-card class="project-create-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><Plus /></el-icon>
            新建项目
          </h2>
          <p class="description">创建新的项目，填写项目基本信息</p>
        </div>
        <el-button @click="$router.go(-1)" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>

      <el-form 
        :model="form" 
        :rules="formRules" 
        ref="formRef" 
        label-width="120px"
        class="project-form"
      >
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="project_id">
              <el-input 
                v-model="form.project_id" 
                placeholder="请输入项目编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="project_name">
              <el-input 
                v-model="form.project_name" 
                placeholder="请输入项目名称"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="项目地点" prop="project_location">
              <el-input 
                v-model="form.project_location" 
                placeholder="请输入项目地点"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="project_manager">
              <el-select 
                v-model="form.project_manager" 
                placeholder="请选择项目经理"
                style="width: 100%"
                clearable
                filterable
                :loading="userLoading"
              >
                <el-option 
                  v-for="user in userList" 
                  :key="user.id" 
                  :label="user.Username" 
                  :value="user.id"
                >
                  <div class="user-option">
                    <span class="user-name">{{ user.Username }}</span>
                    <span class="user-info">{{ user.departement }} - {{ user.worktype }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="项目状态" prop="state">
              <el-select 
                v-model="form.state" 
                placeholder="请选择项目状态"
                style="width: 100%"
                clearable
              >
                <el-option label="计划中" value="计划中" />
                <el-option label="进行中" value="进行中" />
                <el-option label="已完成" value="已完成" />
                <el-option label="暂停" value="暂停" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计开始日期" prop="start_date">
              <el-date-picker
                v-model="form.start_date"
                type="date"
                placeholder="选择开始日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="预计结束日期" prop="end_date">
              <el-date-picker
                v-model="form.end_date"
                type="date"
                placeholder="选择结束日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目预算" prop="budget">
              <el-input-number
                v-model="form.budget"
                :min="0"
                :precision="2"
                :step="1000"
                placeholder="请输入项目预算"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="项目描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述项目内容、目标和要求..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            :rows="3"
            placeholder="其他备注信息（选填）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading" size="large">
            <el-icon><Check /></el-icon>
            创建项目
          </el-button>
          <el-button @click="handleReset" size="large">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button @click="$router.go(-1)" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, ArrowLeft, Check, Refresh, Close } from '@element-plus/icons-vue'
import { createProject } from '../../api/project'
import { getUserList } from '../../api/user'
import { createUserProject } from '../../api/userProject'

const formRef = ref()
const submitLoading = ref(false)
const userLoading = ref(false)
const userList = ref([])

const form = ref({
  project_id: '',
  project_name: '',
  project_location: '',
  project_manager: '',
  state: '计划中',
  start_date: '',
  end_date: '',
  budget: null,
  description: '',
  remark: ''
})

const formRules = {
  project_id: [
    { required: true, message: '请输入项目编号', trigger: 'blur' },
    { min: 3, max: 20, message: '项目编号长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  project_name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 50, message: '项目名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  project_location: [
    { required: true, message: '请输入项目地点', trigger: 'blur' }
  ],
  project_manager: [
    { required: true, message: '请选择项目经理', trigger: 'change' }
  ],
  state: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' },
    { min: 10, max: 500, message: '项目描述长度在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 加载用户列表
async function loadUsers() {
  userLoading.value = true
  try {
    const res = await getUserList()
    userList.value = res.data.records || []
  } catch (error) {
    ElMessage.error('加载用户列表失败')
    console.error('加载用户列表失败:', error)
  } finally {
    userLoading.value = false
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const payload = { ...form.value }
      // 创建项目时自动生成GUID
      const projectId = generateGUID()
      payload.id = projectId
      
      // 创建项目
      await createProject(payload)
      
      // 创建用户项目关联
      if (form.value.project_manager) {
        const userProjectData = {
          Userid: form.value.project_manager,
          Porojectid: form.value.project_id,
          remark: `项目经理关联 - ${form.value.project_name}`
        }
        await createUserProject(userProjectData)
      }
      
      ElMessage.success('项目创建成功！')
      
      // 重置表单
      handleReset()
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        window.history.back()
      }, 1500)
      
    } catch (error) {
      ElMessage.error('创建失败，请重试')
      console.error('创建项目失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 重置表单
function handleReset() {
  formRef.value?.resetFields()
  form.value = {
    project_id: '',
    project_name: '',
    project_location: '',
    project_manager: '',
    state: '计划中',
    start_date: '',
    end_date: '',
    budget: null,
    description: '',
    remark: ''
  }
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.project-create-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.project-create-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 32px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #67c23a;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.back-btn {
  padding: 8px 16px;
  border-radius: 6px;
}

.project-form {
  padding: 20px 0;
}

.user-option {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-name {
  font-weight: 500;
  color: #303133;
}

.user-info {
  font-size: 12px;
  color: #909399;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-date-editor) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

.el-form-item:last-child {
  margin-bottom: 0;
  text-align: center;
}

.el-form-item:last-child .el-button {
  margin: 0 8px;
  padding: 12px 24px;
  border-radius: 8px;
}

@media (max-width: 768px) {
  .project-create-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .project-form {
    padding: 10px 0;
  }
  
  .el-form-item:last-child .el-button {
    margin: 4px;
    width: 100%;
  }
}
</style> 